package com.cn.service.impl;

import java.util.List;

import com.cn.dao.OrderDao;
import com.cn.dao.ProductDao;
import com.cn.dao.impl.OrderDaoImpl;
import com.cn.dao.impl.ProductDaoImpl;
import com.cn.domain.Order;
import com.cn.domain.OrderItem;
import com.cn.domain.Product;
import com.cn.service.OrderService;
import com.cn.utils.JdbcUtils;

public class OrderServiceImpl implements OrderService {

	ProductDao pd = new ProductDaoImpl();
	OrderDao od = new OrderDaoImpl();
	
	public void saveOrder(Order o, List<OrderItem> list) {
		JdbcUtils.getConnectionWithTransaction();
		try {
			for(OrderItem oi:list){
				int pid = oi.getPid();
				Product p = pd.getProductById(pid);
				System.out.println(oi.getBuynum());
				System.out.println(p.getNum());
				if(oi.getBuynum()>p.getNum()){
					throw new RuntimeException(p.getName()+"超过最大库存量！");
				}
				od.saveOrderItem(oi);
				int num = p.getNum()-oi.getBuynum();
				pd.updateProductNum(pid, num);
			}
			od.saveOrder(o);
			JdbcUtils.commit();
		} catch (Exception e) {
			e.printStackTrace();
			JdbcUtils.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	public List<Order> getOrderListByUserId(int id) {
		JdbcUtils.getConnectionWithTransaction();
		List<Order> list = null;
		try {
			list = od.getOrderListByUserId(id);
			JdbcUtils.commit();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			JdbcUtils.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	public Order getListOrderByOrderId(String id) {
		JdbcUtils.getConnectionWithTransaction();
		Order o = null;
		try {
			o = od.getOrderByOrderId(id);
			List<OrderItem> list = od.getListOrderItemByOrderId(id);
			o.setList(list);
			JdbcUtils.commit();
			return o;
		} catch (Exception e) {
			e.printStackTrace();
			JdbcUtils.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}


	public void deleteOrderByOrderId(String id) {
		JdbcUtils.getConnectionWithTransaction();
		try {
			od.deleteOrderByOrderId(id);
			JdbcUtils.commit();
		} catch (Exception e) {
			e.printStackTrace();
			JdbcUtils.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	public void updateOrderStatu(String id) {
		JdbcUtils.getConnectionWithTransaction();
		try {
			od.updateOrderStatu(id);
			JdbcUtils.commit();
		} catch (Exception e) {
			e.printStackTrace();
			JdbcUtils.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	public List<Order> getOrderListByCondition(String id, String receiver) {
		JdbcUtils.getConnectionWithTransaction();
		try {
			List<Order> list = od.getOrderlistByCondition(id, receiver);
			JdbcUtils.commit();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			JdbcUtils.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}


}
